package com.innovation.ic.im.end.web.thread;

import com.alibaba.fastjson.JSON;
import com.google.common.base.Strings;
import com.innovation.ic.b1b.framework.manager.ThreadPoolManager;
import com.innovation.ic.im.end.base.model.im_erp9.GroupMessage;
import com.innovation.ic.im.end.base.pojo.ServiceResult;
import com.innovation.ic.im.end.base.pojo.constant.MessageType;
import com.innovation.ic.im.end.base.service.helper.ServiceImplHelper;
import com.innovation.ic.im.end.base.service.im_erp9.RefGroupAccountService;
import com.innovation.ic.im.end.base.thread.AbstractThread;
import com.innovation.ic.im.end.base.thread.web.SaveGroupMessageReceiverThread;
import com.innovation.ic.im.end.base.vo.im_erp9.GroupMessageVo;
import com.innovation.ic.im.end.base.vo.im_erp9.SendGroupMessageVo;
import com.innovation.ic.im.end.web.endpoint.GroupEndpoint;
import lombok.SneakyThrows;
import org.apache.curator.framework.CuratorFramework;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import javax.websocket.Session;
import java.util.*;

/**
 * 群组聊天环境下，将记录消息保存到group_message表中
 */
public class SaveGroupMessageThread extends AbstractThread implements Runnable {
    private Logger logger = LoggerFactory.getLogger(this.getClass());


    private Long waitingLockTime;

    private String exchange;

    private String urlPrefix;

    private List<String> onlineAccountList;

    private Map<String, Set<GroupEndpoint>> onlineGroupMap;

    public SaveGroupMessageThread(GroupMessage groupMessage, CuratorFramework curatorFramework, Long waitingLockTime, List<String> onlineAccountList,
                                  String exchange, GroupMessageVo groupMessageVo, Map<String, Set<GroupEndpoint>> onlineGroupMap, ThreadPoolManager threadPoolManager) {
        this.groupMessage = groupMessage;
        this.curatorFramework = curatorFramework;
        this.waitingLockTime = waitingLockTime;
        this.onlineAccountList = onlineAccountList;
        this.exchange = exchange;
        this.groupMessageVo = groupMessageVo;
        this.onlineGroupMap = onlineGroupMap;
        this.threadPoolManager = threadPoolManager;
    }

    public SaveGroupMessageThread(GroupMessage groupMessage, CuratorFramework curatorFramework, Long waitingLockTime, List<String> onlineAccountList,
                                  String exchange, GroupMessageVo groupMessageVo, Map<String, Set<GroupEndpoint>> onlineGroupMap, String urlPrefix,
                                  ThreadPoolManager threadPoolManager) {
        this.groupMessage = groupMessage;
        this.curatorFramework = curatorFramework;
        this.waitingLockTime = waitingLockTime;
        this.onlineAccountList = onlineAccountList;
        this.exchange = exchange;
        this.groupMessageVo = groupMessageVo;
        this.onlineGroupMap = onlineGroupMap;
        this.urlPrefix = urlPrefix;
        this.threadPoolManager = threadPoolManager;
    }

    @SneakyThrows
    @Override
    public void run() {
        // 更新最近联系时间
        RefGroupAccountService refGroupAccountService = ServiceImplHelper.getRefGroupAccountService();
        refGroupAccountService.updateLastContactTimeByGroupId(groupMessage.getGroupId());

        // 保存群组消息获取消息id
        ServiceResult<Integer> insertGroupMsgResult = ServiceImplHelper.getGroupMessageService().saveGroupMessage(this.groupMessage);
        Integer groupMessageId = insertGroupMsgResult.getResult();
        groupMessageVo.setGroupMessageId(groupMessageId.toString());

        // 处理账号和群组的操作表数据
        ServiceImplHelper.getRefGroupAccountOperationService().handleRefGroupAccountOperationData(groupMessage.getGroupId(), groupMessage.getFromUserAccount(), curatorFramework, waitingLockTime);

        // 保存群组未读消息数据
        SaveGroupMessageReceiverThread saveGroupMessageReceiverThread = new SaveGroupMessageReceiverThread(groupMessage, onlineAccountList, groupMessageId, groupMessage.getFromUserAccount(), curatorFramework, exchange, waitingLockTime);
        threadPoolManager.execute(saveGroupMessageReceiverThread);

        // 将消息发送给群组中每一个在线的用户,包括自己
        Set<GroupEndpoint> groupEndpointSet = onlineGroupMap.get(groupMessage.getGroupId());
        if(groupEndpointSet != null && groupEndpointSet.size() > 0){
            for (GroupEndpoint groupEndpoint : groupEndpointSet) {
                Session theSession = groupEndpoint.session;
                synchronized (theSession) {
                    if (theSession.isOpen()) {
                        if (groupMessageVo.getType() != null && groupMessageVo.getType().intValue() == MessageType.PICTURE && !Strings.isNullOrEmpty(groupMessageVo.getFilePath())) {
                            if(!groupMessageVo.getFilePath().contains(urlPrefix)){
                                groupMessageVo.setFilePath(urlPrefix + groupMessageVo.getFilePath());
                            }
                        }

                        SendGroupMessageVo sendGroupMessageVo = new SendGroupMessageVo();
                        BeanUtils.copyProperties(groupMessageVo, sendGroupMessageVo);
                        logger.info("sendGroupMessageVo=[{}]", sendGroupMessageVo);
                        theSession.getAsyncRemote().sendText(JSON.toJSONString(sendGroupMessageVo));
                    }
                }

                if (groupMessageVo.getType() != null && groupMessageVo.getType().intValue() == MessageType.TEXT) {
                    logger.info("用户【" + groupMessage.getFromUserAccount() + "】向群组【"
                            + groupMessage.getGroupId() + "】中的用户【" + groupEndpoint.account
                            + "】发送消息【" + groupMessage.getContent() + "】");
                } else {
                    logger.info("用户【" + groupMessageVo.getFromUserAccount() + "】向群组【"
                            + groupMessageVo.getGroupId() + "】中的用户【" + groupEndpoint.account
                            + "】发送图片/文件【" + groupMessageVo.getFilePath() + "】");
                }
            }
        }
    }
}